package com.dongliu.controller;


import ch.qos.logback.core.net.SyslogOutputStream;
import com.dongliu.domain.Admin;
import com.dongliu.domain.User;
import com.dongliu.service.AdminService;
import com.dongliu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private AdminService adminService;

    @GetMapping("/{username}&{password}")
    public Result login(@PathVariable String username, @PathVariable String password, HttpServletRequest request, HttpServletResponse response) {
        User user;
        Admin admin = adminService.login(username, password);
        if(admin == null){
            user = userService.login(username, password);
            if(user == null){
                return new Result(Code.LOGIN_ERR, null, "账号或密码错误，登录失败！");
            }else{
                Admin a = (Admin) request.getSession().getAttribute("admin");
                request.getSession().removeAttribute("admin");
                request.getSession().setAttribute("user", user);
                if(request.getSession().getAttribute("user") != null)
                    System.out.println("session存在");
                return new Result(Code.LOGIN_USER, user, "用户登录成功！");
            }
        }else{
            User u = (User) request.getSession().getAttribute("user");
            System.out.println(u);
            System.out.println("登录管理员账号中");
            request.getSession().removeAttribute("user");
            System.out.println("移除user session");
            request.getSession().setAttribute("admin", admin);
            System.out.println("添加session");
            return new Result(Code.LOGIN_ADMIN, admin, "管理员登录成功！");
        }
    }
}
